﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoYuan.CodeTemplates ;
using BoYuan.DBService ;
using FineUIPro;  
#if DEBUG
namespace BoYuan.CodeGenerator
{ 
    public partial class CreatFineUIProCode2 : System.Web.UI.Page
    {

        private static readonly string accessCon = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", System.Web.HttpContext.Current.Server.MapPath("~/app_data/base.mdb"));


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                cbl_tableNames.DataSource = GetTableInfos();
                cbl_tableNames.DataTextField = "name";
                cbl_tableNames.DataValueField = "name";
                cbl_tableNames.DataBind();

                //
                Bind_ddl_tableName();
                Bind_ddl_column();
                Bind_ddl_tableName2();
                Bind_ddl_column2();

                foreach (int i in Enum.GetValues(typeof(FineuiModule.ModuleType)))
                {
                    ddl_type.Items.Add(new FineUIPro.ListItem(Enum.GetName(typeof(FineuiModule.ModuleType),i), i.ToString()));
                }


                bindGrid();
            }
        }

        #region 事件

        #region 按钮
        protected void Btn_SetSimpleCode_OnClick(object sender, EventArgs e)
        {
            // Alert.Show("生成简单的代码 ");
            if (cbl_tableNames.SelectedValueArray.Length > 0)
            {
                foreach (string item in cbl_tableNames.SelectedValueArray)
                {
                    SetCodeByTableName(item);
                }

                Alert.Show("生成简单代码成功!");
            }
        }

        protected void Btn_SetRelationCode_OnClick(object sender, EventArgs e)
        {
            //设置关联代码
            if (cbl_tableNames.SelectedValueArray.Length > 0)
            {
                foreach (string item in cbl_tableNames.SelectedValueArray)
                {
                    SetCodeByTableName_BLL(item);
                }

                Alert.Show("生成关联代码成功!");
            }
        }

        protected void Btn_AddPageInfoToDB_OnClick(object sender, EventArgs e)
        {

            string sql = string.Format(@"
                            WITH cte AS (
                                     SELECT syso.[name]
                                     FROM   sysobjects AS syso
                                     WHERE  syso.xtype = 'u'
                                            AND syso.[name] NOT IN ('sysadmin', 'sysModule', 'sysRolepopedom')
                                            AND NOT EXISTS
                                                (
                                                    SELECT 1
                                                    FROM   sysModule AS sm
                                                    WHERE  sm.moduleUrl LIKE '%/' + syso.name + 'list.aspx'
                                                )
                                 )

                            INSERT INTO sysModule
                              (
                                parentID,
                                modulePath,
                                moduleName,
                                moduleUrl,
                                moduleIcon,
                                sort,
                                [status],
                                info
                              )
                            SELECT *
                            FROM   (
                                       SELECT 0       AS parentID,
                                              '0,'    AS modulePath,
                                              [name]  AS moduleName,
                                              [name] + '/' + [name] + 'add.aspx' AS moduleUrl,
                                              ''      AS moduleIcon,
                                              1000    AS sort,
                                              0       AS [status],
                                              ''      AS info
                                       FROM   cte
                                       UNION ALL 
                                       SELECT 0       AS parentID,
                                              '0,'    AS modulePath,
                                              [name]  AS moduleName,
                                               [name] + '/' + [name] + 'List.aspx' AS moduleUrl,
                                              ''      AS moduleIcon,
                                              1000    AS sort,
                                              0       AS [status],
                                              ''      AS info
                                       FROM   cte
                                   ) AS temptable
                            ORDER BY
                                   moduleName
                            ");
            var db = BoYuan.DBService.DB_Base.Instance ;
            int tempInt =db.Ado.ExecuteCommand(sql);

            Alert.Show(string.Format("添加了{0}条数据，请根据业务逻辑更改页面组件数据!", tempInt));
        }

        protected void Grid1_OnPageIndexChange(object sender, GridPageEventArgs e)
        {
            bindGrid();
        }

        protected void Button_delete_OnClick(object sender, EventArgs e)
        {
            //批量删除
            string ids = GetDataKeysBySelectedRow(Grid1);
            if (ids.Length == 0)
            {
                Alert.Show("请选择记录！");
                return;
            }

            if (DeleteList(ids))
            {
                bindGrid();
                Alert.Show("删除成功！");
            }
            else
            {
                Alert.Show("删除失败！");
            }

        }

        protected void btn_Relation_OnClick(object sender, EventArgs e)
        {
            //设置关联

            //获取主键表主键
            DataTable keyDt= GetColumnDataByTableName(ddl_tableName.SelectedText, " iskey=1 ");
            if (keyDt == null || keyDt.Rows.Count == 0)
            {
                Alert.Show("关联表没有主键，无法设置关系");
                return;
            }

            
            Configure mo=new Configure();
            mo.column2 = ddl_column2.SelectedValue;
            mo.columnkey = ddl_column.SelectedValue;
            mo.ctrltype = ddl_type.SelectedText;
            mo.key2 = keyDt.Rows[0]["name"].ToString();
            mo.tablename1 = ddl_tableName.SelectedValue;
            mo.tablename2 = ddl_tableName2.SelectedValue;

            if (AddConfigure(mo))
            {
                Alert.Show("添加字段设置成功！");
                bindGrid();
            }
            else
            {
                Alert.Show("添加字段设置失败！");
            }

        }

        protected void btn_setKindEditor_OnClick(object sender, EventArgs e)
        {
            //设置kindeditor
            Configure mo = new Configure();
            mo.column2 = string.Empty;
            mo.columnkey = ddl_column.SelectedValue;
            mo.ctrltype = ddl_type.SelectedText;
            mo.key2 =string.Empty;
            mo.tablename1 = ddl_tableName.SelectedValue;
            mo.tablename2 =string.Empty;

            if (AddConfigure(mo))
            {
                Alert.Show(string.Format("添加{0}设置成功！", ddl_type.SelectedText));
                bindGrid();
            }
            else
            {
                Alert.Show(string.Format("添加{0}设置失败！", ddl_type.SelectedText));
            }
        }

 

        #endregion

        #region 下拉框

        protected void ddl_tableName_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            Bind_ddl_column();
        }

        protected void ddl_tableName2_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            Bind_ddl_column2();
        }

        protected void ddl_type_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            //隐藏
            tlb_bind.Hidden = true;
            tlb_simple.Hidden = true;
            //显示
            switch (int.Parse(ddl_type.SelectedValue))
            {
                case (int)FineuiModule.ModuleType.KindEditor:
                    tlb_simple.Hidden = false;
                    break;
                default:
                    tlb_bind.Hidden = false;
                    break;
            }
        }

        #endregion

        #endregion

        #region 私有方法

        /// <summary>
        /// 绑定表下拉框
        /// </summary>
        private void Bind_ddl_tableName()
        {
            ddl_tableName.DataSource = GetTableInfos();
            ddl_tableName.DataTextField = "name";
            ddl_tableName.DataValueField = "name";
            ddl_tableName.DataBind();
        }

        /// <summary>
        /// 获取选中行的主id
        /// </summary>
        /// <param name="grid">FineUIPro.Grid</param>
        /// <param name="keyNumIndex">第几个主键（从0开始）</param>
        /// <returns></returns>
        public static string GetDataKeysBySelectedRow(Grid grid, int keyNumIndex = 0)
        {
            //需要正确设置grid DataKeyNames主键列名
            int[] selections = grid.SelectedRowIndexArray;//获取选中行
            if (selections.Length == 0)
            {
                return string.Empty;
            }

            return string.Join(",", selections);
        }

        /// <summary>
        /// 绑定表下拉框
        /// </summary>
        private void Bind_ddl_tableName2()
        {
            ddl_tableName2.DataSource = GetTableInfos();
            ddl_tableName2.DataTextField = "name";
            ddl_tableName2.DataValueField = "name";
            ddl_tableName2.DataBind();
        }

        private void Bind_ddl_column()
        {
            ddl_column.DataSource = GetColumnDataByTableName(ddl_tableName.SelectedText, " iskey=0 ");//排除主键
            ddl_column.DataTextField = "name";
            ddl_column.DataValueField = "name";
            ddl_column.DataBind();
            if (ddl_column.Items.Count > 0)
            {
                ddl_column.Items[0].Selected = true;
            }
        }
        private void Bind_ddl_column2()
        {
            ddl_column2.DataSource = GetColumnDataByTableName(ddl_tableName2.SelectedText, " iskey=0 ");//排除主键
            ddl_column2.DataTextField = "name";
            ddl_column2.DataValueField = "name";
            ddl_column2.DataBind();
            if (ddl_column2.Items.Count > 0)
            {
                ddl_column2.Items[0].Selected = true;
            }
        }

        private void bindGrid()
        {
            int pageCount = 0;
            int recordCount = 0;
            AccessHelper access=new AccessHelper(accessCon);
            Grid1.DataSource = access.ExecutePager(Grid1.PageIndex, Grid1.PageSize, "id", " * ", " configure ", string.Empty, null,
                " tablename1 ", out pageCount,out recordCount);
            Grid1.DataBind();

            Grid1.RecordCount = recordCount;
            //Grid1.PageCount = pageCount;

            
        }

        /// <summary>
        /// 获取表信息
        /// </summary>
        /// <returns></returns>
        private DataTable GetTableInfos()
        {
            string sql = "select [name] from sysobjects where xtype='u'  and   [name] not in ( 'sysAdmin' ,'SysModule','SysRolepopedom') order by [name]";
            var db = DBService.DB_Base.Instance ;
            return db.Ado.GetDataTable(sql);
        }

        /// <summary>
        /// 生成页面代码，根据表
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        private void SetCodeByTableName(string tableName)
        {
            DataTable dt = GetColumnDataByTableName(tableName);//字段信息集合
            string namespace2Str = txb_Path.Text.Trim().Replace("/", ".");

            string savePath = HttpContext.Current.Server.MapPath("~/" + txb_Path.Text + "/" + tableName + "/");
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath); //在根目录下建立文件夹
            }

            //add
            FineuiAddCSTemplate addCsTemplate = new FineuiAddCSTemplate()
            {
                Items = dt,
                NamespaceStr = txb_NameSpace.Text,
                Namespace2Str = namespace2Str,
                ClassnameStr = txb_BaseClassName.Text,
                TableName = tableName
            };
            string templateInfo = addCsTemplate.TransformText();
            System.IO.File.WriteAllText(savePath + tableName + "Add.aspx.cs", templateInfo, Encoding.UTF8);

            FineuiAddTemplate addTemplate = new FineuiAddTemplate()
            {
                Items = dt,
                NamespaceStr = txb_NameSpace.Text,
                Namespace2Str = namespace2Str,
                ClassnameStr = txb_BaseClassName.Text,
                TableName = tableName
            };
            templateInfo = addTemplate.TransformText();
            System.IO.File.WriteAllText(savePath + tableName + "Add.aspx", templateInfo, Encoding.UTF8);

            //List
            FineuiListCSTemplate listCsTemplate = new FineuiListCSTemplate()
            {
                Items = dt,
                NamespaceStr = txb_NameSpace.Text,
                Namespace2Str = namespace2Str,
                ClassnameStr = txb_BaseClassName.Text,
                TableName = tableName
            };
            templateInfo = listCsTemplate.TransformText();
            System.IO.File.WriteAllText(savePath + tableName + "List.aspx.cs", templateInfo, Encoding.UTF8);

            //带视图页面
            if (cb_isHaveViewPage.Checked)
            {
                //List
                FineuiListTemplate listTemplate = new FineuiListTemplate()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = listTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "List.aspx", templateInfo, Encoding.UTF8);

                //View
                FineuiViewCSTemplate viewCsTemplate = new FineuiViewCSTemplate()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = viewCsTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "View.aspx.cs", templateInfo, Encoding.UTF8);

                FineuiViewTemplate viewTemplate = new FineuiViewTemplate()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = viewTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "View.aspx", templateInfo, Encoding.UTF8);
            }
            else
            {
                //List
                FineuiListTemplate_noView listTemplate = new FineuiListTemplate_noView()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = listTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "List.aspx", templateInfo, Encoding.UTF8);
            }


        } 
        
        /// <summary>
        /// 生成页面代码，根据表
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        private void SetCodeByTableName_BLL(string tableName)
        {
            DataTable dt = GetColumnDataByTableName(tableName).Copy();//字段信息集合
            string namespace2Str = txb_Path.Text.Trim().Replace("/", ".");

            dt.Columns.Add("ctrltype");
            dt.Columns.Add("tablename2");
            dt.Columns.Add("column2");
            dt.Columns.Add("key2");

            var list = GetList(string.Format(" tablename1='{0}' ", tableName));
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (list[i].columnkey == dt.Rows[j]["NAME"].ToString())
                        {
                            dt.Rows[j]["ctrltype"] = list[i].ctrltype;
                            dt.Rows[j]["tablename2"] = list[i].tablename2;
                            dt.Rows[j]["column2"] = list[i].column2;
                            dt.Rows[j]["key2"] = list[i].key2;
                        }
                    }
                }
            }



            string savePath = HttpContext.Current.Server.MapPath("~/" + txb_Path.Text + "/" + tableName + "/");
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath); //在根目录下建立文件夹
            }

            //add
            SetCode.Fineui_BLL.FineuiAddCSTemplate addCsTemplate = new SetCode.Fineui_BLL.FineuiAddCSTemplate()
            {
                Items = dt,
                NamespaceStr = txb_NameSpace.Text,
                Namespace2Str = namespace2Str,
                ClassnameStr = txb_BaseClassName.Text,
                TableName = tableName
            };
            string templateInfo = addCsTemplate.TransformText();
            System.IO.File.WriteAllText(savePath + tableName + "Add.aspx.cs", templateInfo, Encoding.UTF8);

            SetCode.Fineui_BLL.FineuiAddTemplate addTemplate = new SetCode.Fineui_BLL.FineuiAddTemplate()
            {
                Items = dt,
                NamespaceStr = txb_NameSpace.Text,
                Namespace2Str = namespace2Str,
                ClassnameStr = txb_BaseClassName.Text,
                TableName = tableName
            };
            templateInfo = addTemplate.TransformText();
            System.IO.File.WriteAllText(savePath + tableName + "Add.aspx", templateInfo, Encoding.UTF8);

            //List
            SetCode.Fineui_BLL.FineuiListCSTemplate listCsTemplate = new SetCode.Fineui_BLL.FineuiListCSTemplate()
            {
                Items = dt,
                NamespaceStr = txb_NameSpace.Text,
                Namespace2Str = namespace2Str,
                ClassnameStr = txb_BaseClassName.Text,
                TableName = tableName
            };
            templateInfo = listCsTemplate.TransformText();
            System.IO.File.WriteAllText(savePath + tableName + "List.aspx.cs", templateInfo, Encoding.UTF8);

            //带视图页面
            if (cb_isHaveViewPage.Checked)
            {
                //List
                SetCode.Fineui_BLL.FineuiListTemplate listTemplate = new SetCode.Fineui_BLL.FineuiListTemplate()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = listTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "List.aspx", templateInfo, Encoding.UTF8);

                //View
                SetCode.Fineui_BLL.FineuiViewCSTemplate viewCsTemplate = new SetCode.Fineui_BLL.FineuiViewCSTemplate()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = viewCsTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "View.aspx.cs", templateInfo, Encoding.UTF8);

                SetCode.Fineui_BLL.FineuiViewTemplate viewTemplate = new SetCode.Fineui_BLL.FineuiViewTemplate()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = viewTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "View.aspx", templateInfo, Encoding.UTF8);
            }
            else
            {
                //List
                SetCode.Fineui_BLL.FineuiListTemplate_noView listTemplate = new SetCode.Fineui_BLL.FineuiListTemplate_noView()
                {
                    Items = dt,
                    NamespaceStr = txb_NameSpace.Text,
                    Namespace2Str = namespace2Str,
                    ClassnameStr = txb_BaseClassName.Text,
                    TableName = tableName
                };
                templateInfo = listTemplate.TransformText();
                System.IO.File.WriteAllText(savePath + tableName + "List.aspx", templateInfo, Encoding.UTF8);
            }


        }

        /// <summary>
        /// 获取字段信息集合，根据表
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        private DataTable GetColumnDataByTableName(string tableName)
        {
            return GetColumnDataByTableName(tableName, String.Empty);
        }

        /// <summary>
        /// 获取字段信息集合，根据表
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="whereSql">条件</param>
        /// <returns></returns>
        private DataTable GetColumnDataByTableName(string tableName, string whereSql)
        {
            /*
             string sql = @"                
                     select name,isnullable,
                 (select [VALUE] 
                  from sys.extended_properties 
                  WHERE syscolumns.id=sys.extended_properties.major_id and syscolumns.colid=sys.extended_properties.minor_id ) AS info,
                             (select name from systypes WHERE syscolumns.xusertype=systypes.xusertype) AS typename,
                         (SELECT CASE WHEN EXISTS(SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='" + tableName + @"' AND COLUMN_NAME=syscolumns.name) THEN 1 ELSE 0 END )            
                         as iskey,
                         (select syscomments.text FROM syscomments  WHERE syscolumns.cdefault= syscomments.id) AS defaultValue
                           from syscolumns where id=object_id('" + tableName + @"') 
                          ";
              */
            string sql = string.Format(@"
                        select * from (
                        SELECT c.NAME,
                               c.isnullable,
                               ep.[value]                         AS info,
                               st.NAME                            AS typename,
                               sc.text                            AS defaultValue,
                               (
                                   SELECT CASE 
                                               WHEN EXISTS(
                                                        SELECT 1
                                                        FROM   INFORMATION_SCHEMA.KEY_COLUMN_USAGE
                                                        WHERE  TABLE_NAME = '{0}'
                                                               AND COLUMN_NAME = c.name
                                                    ) THEN 1
                                               ELSE 0
                                          END
                               )                                  AS iskey
       	                        columnproperty(c.id,c.name, 'IsIdentity')  as  IsIdentity,
                                columnproperty(c.id,c.name,'PRECISION') as lenght
                        FROM   syscolumns                         AS c
                               LEFT JOIN sys.extended_properties  AS ep
                                    ON  c.id = ep.major_id
                                    AND c.colid = ep.minor_id
                               LEFT JOIN systypes                 AS st
                                    ON  c.xusertype = st.xusertype
                               LEFT JOIN syscomments              AS sc
                                    ON  c.cdefault = sc.id
                        WHERE  c.id = OBJECT_ID('{0}') ) as columnInfo 
            ", tableName);
            if (whereSql.Length > 0)
            {
                sql += string.Format(" where {0} ", whereSql);
            }

            //name(字段名),isnullable(是否为null),info(字段说明),typename(字段类型),iskey(是否为主键),defaultValue(默认值)
            var db = DBService.DB_Base.Instance ;
            return db.Ado.GetDataTable(sql);//字段信息集合
        }
        #endregion

        #region access
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool AddConfigure(Configure model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into configure(");
            strSql.Append("tablename1,columnkey,ctrltype,tablename2,column2,key2)");
            strSql.Append(" values (");
            strSql.Append("@tablename1,@columnkey,@ctrltype,@tablename2,@column2,@key2)");
            OleDbParameter[] parameters = {
					new OleDbParameter("@tablename1", OleDbType.VarChar,255),
					new OleDbParameter("@columnkey", OleDbType.VarChar,255),
					new OleDbParameter("@ctrltype", OleDbType.VarChar,255),
					new OleDbParameter("@tablename2", OleDbType.VarChar,255),
					new OleDbParameter("@column2", OleDbType.VarChar,255),
					new OleDbParameter("@key2", OleDbType.VarChar,255)};
            parameters[0].Value = model.tablename1;
            parameters[1].Value = model.columnkey;
            parameters[2].Value = model.ctrltype;
            parameters[3].Value = model.tablename2;
            parameters[4].Value = model.column2;
            parameters[5].Value = model.key2;

            AccessHelper accDb=new AccessHelper(accessCon);

            return accDb.ExecSql(strSql.ToString(), parameters).Length==0;
        }

        public bool DeleteList(string idlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from configure ");
            strSql.Append(" where id in (" + idlist + ")  ");
            AccessHelper accDb = new AccessHelper(accessCon);
            return accDb.ExecSql(strSql.ToString()).Length == 0;
        }

        public List<Configure> GetList(string sqlWhere)
        {
            string sql = string.Format(" select * from Configure {0} ", sqlWhere.Length==0? string.Empty:string.Format(" where {0} ",sqlWhere));
            AccessHelper access=new AccessHelper(accessCon);
            DataTable dt = access.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                List<Configure> list = new List<Configure>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    list.Add(DataRowToModel(dt.Rows[i]));
                }

                return list;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        private Configure DataRowToModel(DataRow row)
        {
            Configure model = new Configure();
            if (row != null)
            {
                if (row["id"] != null && row["id"].ToString() != "")
                {
                    model.id = int.Parse(row["id"].ToString());
                }
                if (row["tablename1"] != null)
                {
                    model.tablename1 = row["tablename1"].ToString();
                }
                if (row["columnkey"] != null)
                {
                    model.columnkey = row["columnkey"].ToString();
                }
                if (row["ctrltype"] != null)
                {
                    model.ctrltype = row["ctrltype"].ToString();
                }
                if (row["tablename2"] != null)
                {
                    model.tablename2 = row["tablename2"].ToString();
                }
                if (row["column2"] != null)
                {
                    model.column2 = row["column2"].ToString();
                }
                if (row["key2"] != null)
                {
                    model.key2 = row["key2"].ToString();
                }
            }
            return model;
        }


        #endregion

       
    }
}
#endif